import fetch from '../../utils/services'
const app = getApp()
Page({
  data: {
    type: 'userInfo',
  },
  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '授权'
    })
    this.setData({
      type: options.type,
      openId: options.openId || '',
      unionId: options.unionId || '',
      wxName: options.wxName || '',
      wxPic: options.wxPic || ''
    })
  },
  modal_click_Hidden: function () {
    wx.navigateBack()
  },
  onGotUserInfo: function(e) {
    if (e.detail.rawData) {
      app.logIn()
      this.goBack()
    }
    // else {
    //   wx.navigateBack()
    // }
  },
  onGetPhoneNumber: function(e) {
    if (e.detail.encryptedData) {
      wx.login({
        success: res => {
          fetch.post('/user/decodeUserInfo', {
            code: res.code,
            iv: e.detail.iv,
            encryptedData: e.detail.encryptedData,
            type: 2, //获取手机号
          }).then(data => {
            const phoneNum = data.phoneNumber
            const { unionId, openId, wxName, wxPic }  = this.data
            const param = {
              openId, type: 3, unionId, wxName, wxPic, phoneNum
            }
            fetch.post('/user/bindPhone', param).then((result) => {
              app.logIn()
              this.goBack()
            }).catch(err => {
              wx.showToast({
                title: err.message || '获取信息失败',
                icon: 'none',
                duration: 2000
              })
            })
          }).catch(err => {
            wx.showToast({
              title: err.message || '获取信息失败',
              icon: 'none',
              duration: 2000
            })
          })
        }
      })
    }
    // else {
    //   wx.navigateBack()
    // }
  },
  goBack: function() {
    // wx.navigateBack()
    if (app.globalData.page === 'index') {
      wx.reLaunch({
        url: `/pages/index/index`,
        fail: err => {
          console.log(err)
        }
      })
    } else {
      wx.reLaunch({
        url: `/pages/home/index`,
        fail: err => {
          console.log(err)
        }
      })
    }
  }
})
